package top.codetheory.thread._001_打断;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class _003_二阶段终止模式_使用打断模式 {
    public static void main(String[] args) {
        Monitor monitor = new Monitor();
        monitor.start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        monitor.stop();
    }

    /**
     * <img src="https://gitee.com/codetheory/img-on1/raw/master/img01/1713658260425-2024-4-2108:11:00.png"  />
     */
    static class Monitor {
        private Thread thread;

        public void start() {
            thread = new Thread(() -> {
                while (true) {
                    Thread current = Thread.currentThread();
                    if (current.isInterrupted()) {
                        log.info("料理后事, 释放资源");
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        current.interrupt();  // 如果是在阻塞状态被打断的话, 打断标记还是为false, 所以要手动设置打断标记
                    }
                    log.info("执行监控任务");
                }
            }, "t1");

            thread.start();

        }

        public void stop() {
            thread.interrupt();
        }

    }
}